package com.boyadegroot.divelog.ui.diver.tabs;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.TextView;

import com.boyadegroot.divelog.R;
import com.boyadegroot.divelog.data.DiveLogData;
import com.boyadegroot.divelog.data.DiveLogDatabaseContract;
import com.boyadegroot.divelog.models.DiveCountry;
import com.boyadegroot.divelog.models.DiveLocation;
import com.boyadegroot.divelog.models.DiveSite;
import com.boyadegroot.divelog.utilities.DateUtils;

public class DiverDivesAdapter extends SimpleCursorAdapter {

    public DiverDivesAdapter(Context context, int layout) {
        super(context, layout, null, new String[0], new int[0], 0);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        long diveId = cursor.getLong(cursor.getColumnIndex(DiveLogDatabaseContract.Dives._ID));
        view.setTag(R.id.tag_dive_id, diveId);
        int number = cursor.getPosition() + 1;
        TextView numberView = (TextView) view.findViewById(R.id.number);
        numberView.setIncludeFontPadding(false);
        numberView.setText(Integer.toString(number));
        view.setTag(R.id.tag_dive_number, number);
        int count = cursor.getCount();
        if (count > 999) {
            numberView.setWidth(160);
        } else if(count > 99) {
            numberView.setWidth(125);
        } else { // count < 100
            numberView.setWidth(100);
        }
        Long siteId = cursor.getLong(cursor.getColumnIndex(DiveLogDatabaseContract.Dives.COLUMN_NAME_SITE_ID));
        DiveLogData data = DiveLogData.getInstance(context);
        DiveSite site = data.getDiveSite(siteId);
        DiveLocation location = site.getLocation();
        DiveCountry country = location.getCountry();
        TextView siteView = (TextView) view.findViewById(R.id.site);
        siteView.setText(site.getName());
        TextView locationView = (TextView) view.findViewById(R.id.location);
        locationView.setText(String.format("%s (%s)", location.getName(), country.getName()));
        long date = cursor.getLong(cursor.getColumnIndex(DiveLogDatabaseContract.Dives.COLUMN_NAME_STARTTIME));
        TextView dateView = (TextView) view.findViewById(R.id.date);
        dateView.setText(DateUtils.getLongDateTimeString(date));
        super.bindView(view, context, cursor);
    }
}
